package com.jetpackframework.retrofit.converter;

import androidx.annotation.Nullable;

import com.gwm.annotation.ftp.FTP;
import com.gwm.annotation.http.Query;
import com.jetpackframework.ftp.FTPTask;
import com.jetpackframework.retrofit.Converter;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class FTPRequestConverter implements Converter<FTPTask> {
    private static FTPRequestConverter converter;
    public static synchronized Converter get(){
        if (converter == null){
            converter = new FTPRequestConverter();
        }
        return converter;
    }

    @Nullable
    @Override
    public FTPTask convert(Method method, Object[] args) {
        FTPTask ftpTask = new FTPTask();
        FTP ftp = method.getAnnotation(FTP.class);
        ftpTask.fileName = ftp.fileName();
        ftpTask.ftpUrl = ftp.url();
        ftpTask.port = ftp.port();
        ftpTask.filePath = ftp.filePath();
        ftpTask.ftpFile = ftp.ftpFile();
        ftpTask.password = ftp.password();
        ftpTask.username = ftp.username();
        Annotation[][] annotations = method.getParameterAnnotations();
        for (int i = 0; i < annotations.length; i++) {     //i:第几个参数的注解
            if (annotations[i].length > 0) {
                for (int j = 0; j < annotations[i].length; j++) {  //j: 第i个参数上的第j个注解
                    if(annotations[i][j] instanceof Query) {
                        Query query = (Query) annotations[i][j];
                        String key = query.value();
                        Object value = args[i];
                        try {
                            Field field = FTPTask.class.getField(key);
                            field.setAccessible(true);
                            field.set(ftpTask,value);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return ftpTask;
    }
}
